<?php

namespace app\commission;

use app\models\distribution\DistributionGroup;
use app\models\order\Order;
use app\models\order\OrderItem;
use app\models\product\Product;
use app\models\product\ProductAreaList;
use app\models\user\User;
use app\models\user\UserAccount;
use app\models\user\UserCommission;
use app\models\user\UserLevel;
use app\services\Chain;
use yii\helpers\ArrayHelper;

/**
 *
 * 升级
 *
 * Class UpLevel
 * @package app\commission
 */
class UpLevel
{
    public static function up(Order $order)
    {
        // self::upMember($order);
        // self::upGroup($order);

        // 爆品区 (才处理升级)
        $first_order_item = OrderItem::find()
            ->where(['order_id' => $order->id])
            ->orderBy(['id' => SORT_ASC])
            ->limit(1)
            ->one();
        $product_id = $first_order_item->product_id;
        if (ProductAreaList::checkInArea($product_id, Product::$areaMap['BAO'])) {
            // self::orderUp($order);

            // 先返佣, 后升级
            self::calcCommission($order);
            self::upUser($order);

        }

    }

    // 升级
    private static function upUser(Order $order) {
        $total = $order->total_pay;

        // $levels = UserLevel::find()
        //     ->orderBy(['id' => SORT_DESC])
        //     ->all();
        $user = User::findOne(['id' => $order->user_id]);

        if ($total >= 399) {
            if ($user->level < UserLevel::$keys['member']) {
                $user->level = UserLevel::$keys['member'];
                $user->save();
            }
        }

        // 处理上级升级
        self::u($user->id);
    }

    private static function u($user_id)
    {
        $referrer = Chain::getReferrer($user_id, true);

        // 下面三个if, 如果逐步升级就要加else, 否则去掉else
        if ($referrer) {
            // 经理, 直推8位店主
            if ($referrer->level < UserLevel::$keys['vip1']) {
                $children = User::find()
                    ->where(['referrer_id' => $referrer->id])
                    ->andWhere(['>=', 'level', UserLevel::$keys['member']])
                    ->count();
                if ($children >= 6) {
                    $referrer->level = UserLevel::$keys['vip1'];
                    $referrer->save();
                }
            }
            // 总监, 直推50位店主, 或直推5位经理
            if ($referrer->level < UserLevel::$keys['vip2']) {
                $children1 = User::find()
                    ->where(['referrer_id' => $referrer->id])
                    ->andWhere(['>=', 'level', UserLevel::$keys['member']])
                    ->count();
                $children2 = User::find()
                    ->where(['referrer_id' => $referrer->id])
                    ->andWhere(['>=', 'level', UserLevel::$keys['vip1']])
                    ->count();
                if ($children1 >= 31 || $children2 >= 5) {
                    $referrer->level = UserLevel::$keys['vip2'];
                    $referrer->save();
                }
            }
            // 合伙人, 直推5位总监
            if ($referrer->level < UserLevel::$keys['vip3']) {
                $children = User::find()
                    ->where(['referrer_id' => $referrer->id])
                    ->andWhere(['>=', 'level', UserLevel::$keys['vip2']])
                    ->count();
                if ($children >= 5) {
                    $referrer->level = UserLevel::$keys['vip3'];
                    $referrer->save();
                }
            }

            // chain
            self::u($referrer->id);
        }
    }

    // 返佣
    private static function calcCommission(Order $order)
    {
        // 直推奖
        $referrer = Chain::getReferrer($order->user_id, true);
        if ($referrer) {
            $balance = $order->total_quantity * 80;
            self::saveC($referrer->id, $order->user_id, $order->id, $balance, 1, '直推奖');

            // 间推奖
            $referrer2 = Chain::getReferrer($referrer->id, true);
            if ($referrer2) {
                $balance = $order->total_quantity * 40;
                self::saveC($referrer2->id, $order->user_id, $order->id, $balance, 2, '间推奖');
            }
        }

        $user = User::findOne(['id' => $order->user_id]);

        // 平级奖(经理, 总监, 合伙人才有)
        // 平级奖:
        // 找到购买者链上有身份(经理,总监,合伙人), 再找此人的平级链, 给返佣
        // $user = User::findOne(['id' => $order->user_id]);
        // if ($user && $user->level > UserLevel::$keys['member']) {
        //     $referrer = Chain::getReferrerChain($user->id, [$user->level], true);
        //     if (count($referrer) > 0) {
        //         $r = $referrer[0];
        //         $balance = $order->total_quantity * 8;
        //         self::saveC($r->id, $order->user_id, $order->id, $balance, 3, '平级奖');
        //     }
        // }

        // 1
        $referrer = Chain::getReferrerChain($order->user_id,
            [UserLevel::$keys['vip1'], UserLevel::$keys['vip2'], UserLevel::$keys['vip3']], true);
        // $referrer = [Chain::getReferrer($order->user_id, true)];
        if (count($referrer) > 0) {
            $r = $referrer[0];
            // 2
            // $r2 = Chain::getReferrerChain($r->id, [$r['level']], true);
            $r2 = Chain::getReferrerChain($r->id,
                [UserLevel::$keys['vip1'], UserLevel::$keys['vip2'], UserLevel::$keys['vip3']], true);
            // $r2 = Chain::getReferrerChain($r->id, [], true);
            if (count($r2) > 0) {
                $balance = $order->total_quantity * 8;
                // $r2 = $r2[0];
                // self::saveC($r2->id, $order->user_id, $order->id, $balance, 3, '平级奖');

                // 要处理多个
                $use_vip1 = false;
                $use_vip2 = false;
                foreach ($r2 as $item) {

                    if ($item->level == UserLevel::$keys['vip1'] && !$use_vip1) {
                        $use_vip1 = true;
                        self::saveC($item->id, $order->user_id, $order->id, $balance, 3, '平级奖');
                    }

                    if ($item->level == UserLevel::$keys['vip2'] && !$use_vip2) {
                        $use_vip2 = true;
                        $use_vip1 = true;
                        self::saveC($item->id, $order->user_id, $order->id, $balance, 3, '平级奖');
                    }

                    if ($item->level == UserLevel::$keys['vip3']) {
                        self::saveC($item->id, $order->user_id, $order->id, $balance, 3, '平级奖');
                        break;
                    }
                }
            }
        }

        // 团队极差奖(40, 60, 60注意这里有个60)
        $use_1 = 0;
        $use_2 = 0;

        $balance1 = $order->total_quantity * 40;
        $balance2 = $order->total_quantity * 60;
        $balance3 = $order->total_quantity * 60;

        $referrers = Chain::getReferrerChain($user->id, [], true);
        if ($referrers) {
            foreach ($referrers as $v) {
                if ($v->level < UserLevel::$keys['vip1']) {
                    continue;
                }
                // 低推高没有
                if ($v->level < $user->level) {
                    continue;
                }
                // var_dump($v->level);exit;

                if ($v->level == UserLevel::$keys['vip1'] && $use_1 == 0) {
                    $use_1 = $balance1;
                    self::saveC($v->id, $order->user_id, $order->id, $use_1, 4, '团队奖');
                }
                if ($v->level == UserLevel::$keys['vip2'] && $use_2 == 0) {
                    $use_2 = $balance2 - $use_1;
                    self::saveC($v->id, $order->user_id, $order->id, $use_2, 4, '团队奖');
                }
                if ($v->level == UserLevel::$keys['vip3']) {
                    $use_3 = $balance3 - $use_1 - $use_2;
                    self::saveC($v->id, $order->user_id, $order->id, $use_3, 4, '团队奖');
                    break;
                }
            }
        }

        // 分红奖: 平台整个的, 不是关系链上的
        // $referrers = Chain::getReferrerChain($order->user_id, [UserLevel::$keys['vip3']], true);
        $referrers = User::find()
            ->where(['level' => UserLevel::$keys['vip3']])
            ->all();
        $count = count($referrers);
        if ($count > 0) {
            $balance = $order->total_quantity * 8;
            $balance = $balance / $count;
            foreach ($referrers as $r) {
                self::saveC($r->id, $order->user_id, $order->id, $balance, 10, '分红奖');
            }
        }
    }

    private static function saveC($user_id, $fans_id, $order_id, $balance, $type, $name)
    {
        if ($balance > 0) {
            $model = new UserCommission();
            $model->user_id = $user_id;
            $model->fans_id = $fans_id;
            $model->order_id = $order_id;
            $model->balance = $balance;
            // 如果是分红(线下发放)
            // received
            if ($type == 10) {
                $model->status = 10;
            } else {
                $model->status = 0;
            }
            $model->award_name = $name;
            $model->award_type = $type;
            $model->save();

            // change received commission
            if ($type != 10) {
                $account = UserAccount::findOne(['user_id' => $user_id]);
                if ($account) {
                    // $account->balance += $balance;
                    $account->await_balance += $balance;
                    $account->save();
                }
            }

        }
    }

    // ========================================================================================

    // 下单 升级成 会员
    private static function upMember(Order $order)
    {
        $user = User::findOne(['id' => $order->user_id]);
        $member = UserLevel::$keys['member'];

        if ($user->level < $member) {
            $user->level = $member;
            $user->save();
        }
    }

    // 团队99升级
    private static function upGroup(Order $order)
    {
        $set = DistributionGroup::getLastOne();

        /*
         * order > 99
         *  => vip1 201
         */
        if ($order->is_group == 1 && $order->total_pay - $order->total_freight >= $set->order_amount) {

            $user = User::findOne(['id' => $order->user_id]);
            $vip1 = UserLevel::$keys['vip1'];

            if ($user->level < $vip1) {
                $user->level = $vip1;
                $user->save();
            }
        }
    }

    // order up
    private static function orderUp(Order $order)
    {
        /*
         * 一次性下单
         */
        $total1 = 500;
        $total2 = 1000;

        $level1 = UserLevel::$keys['svip1'];
        $level2 = UserLevel::$keys['svip2'];

        $user = User::findOne(['id' => $order->user_id]);

        // 初级代理
        if ($order->is_group == 0 && $order->total_pay - $order->total_freight >= $total1) {
            if ($user->level < $level1) {
                $user->level = $level1;
                $user->save();
            }
        }

        // 高级代理
        if ($order->is_group == 0 && $order->total_pay - $order->total_freight >= $total2) {
            if ($user->level < $level2) {
                $user->level = $level2;
                $user->save();
            }
        }

        // 高级身份
        $referrers = Chain::getReferrerChain($user->id);
        self::upV($referrers);
    }

    // 合伙人 / 股东
    private static function upV($referrers)
    {
        foreach ($referrers as $item) {
            // 必须是初级代理才可以升级
            if ($item['level'] < UserLevel::$keys['svip1']) {
                continue;
            }

            // 必须有3条线
            $first_recommend = Chain::getChildren($item['id']);
            if (count($first_recommend) < 3) {
                continue;
            }

            // v1
            $first_recommend_level = ArrayHelper::getColumn($first_recommend, 'level');
            $vip_count = 0;
            foreach ($first_recommend_level as $v) {
                if ($v >= UserLevel::$keys['svip1']) {
                    $vip_count++;
                }
            }
            self::saveV($item['id'], UserLevel::$keys['v1'], $vip_count);

            // v & w ++
            $v1_count = 0;
            $v2_count = 0;
            $v3_count = 0;
            $v5_count = 0;
            $w1_count = 0;
            $w2_count = 0;

            // $first_recommend_id = ArrayHelper::getColumn($first_recommend, 'id');
            // var_dump($first_recommend_id);exit;

            // 每条线
            foreach ($first_recommend as $first) {

                // 一条线上所有(只算一个)
                // 团队线(包括自己)
                $children = Chain::getChildrenAll($first['id']);
                $children = array_merge([$first], $children);

                foreach ($children as $v) {
                    if ($v['level'] >= UserLevel::$keys['v1']) {
                        $v1_count++;
                        break;
                    }
                }
                foreach ($children as $v) {
                    if ($v['level'] >= UserLevel::$keys['v2']) {
                        $v2_count++;
                        break;
                    }
                }
                foreach ($children as $v) {
                    if ($v['level'] >= UserLevel::$keys['v3']) {
                        $v3_count++;
                        break;
                    }
                }
                foreach ($children as $v) {
                    if ($v['level'] >= UserLevel::$keys['v5']) {
                        $v5_count++;
                        break;
                    }
                }
                foreach ($children as $v) {
                    if ($v['level'] >= UserLevel::$keys['w1']) {
                        $w1_count++;
                        break;
                    }
                }
                foreach ($children as $v) {
                    if ($v['level'] >= UserLevel::$keys['w2']) {
                        $w2_count++;
                        break;
                    }
                }
            }
            // var_dump(
            //     $v1_count,
            //     $v2_count,
            //     $v3_count,
            //     $v5_count,
            //     $w1_count,
            //     $w2_count
            // );
            // exit;

            self::saveV($item['id'], UserLevel::$keys['v2'], $v1_count, 3);
            self::saveV($item['id'], UserLevel::$keys['v3'], $v2_count, 3);
            self::saveV($item['id'], UserLevel::$keys['v5'], $v3_count, 3);

            self::saveV($item['id'], UserLevel::$keys['w1'], $v5_count, 3);
            self::saveV($item['id'], UserLevel::$keys['w2'], $w1_count, 3);
            self::saveV($item['id'], UserLevel::$keys['w3'], $w2_count, 3);

        }
    }

    private static function saveV($user_id, $level, $has, $quantity = 3)
    {
        if ($has >= $quantity) {
            $user = User::findOne(['id' => $user_id]);
            if ($user && $user->level < $level) {
                $user->level = $level;
                $user->save();
            }
        }
    }
}